/*
 * GroupDaoJdbcImpl.java
 *
 * Project: TECHWATCH - TESTING TECHNOLOGIES
 *
 * Copyright 2008 by ELCA Informatique SA
 * Av. de la Harpe 22-24, 1000 Lausanne 13
 * All rights reserved.
 *
 * This software is the confidential and proprietary information
 * of ELCA Informatique SA. ("Confidential Information"). You
 * shall not disclose such Confidential Information and shall
 * use it only in accordance with the terms of the license
 * agreement you entered into with ELCA.
 */

package ch.elca.training.dao.impl;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import ch.elca.training.dao.GroupDao;
import ch.elca.training.dao.generic.GenericDaoJdbcImpl;
import ch.elca.training.dom.Group;

@Repository
public class GroupDaoJdbcImpl extends GenericDaoJdbcImpl<Group> implements
		GroupDao {

	private static final String SQL_GET_ALL = "select * from group";
	private static final String SQL_READ = "select * from group where id = ?";
	private static final String SQL_CREATE = "insert into group (id, name, visa_leader) values (?, ?, ?)";
	private static final String SQL_UPDATE = "update group set name = ?, visa_leader = ? where id = ?";
	private static final String SQL_DELETE = "delete from group where id = ?";

	@Override
	public void create(final Group newInstance) {
		getJdbcTemplate().update(SQL_CREATE, getNextSequenceValue(),
				newInstance.getName(), newInstance.getVisaLeader());
	}

	@Override
	public Group read(Long id) {

		return getJdbcTemplate().queryForObject(SQL_READ, new Object[] { id },
				new RowMapper<Group>() {

					@Override
					public Group mapRow(ResultSet rs, int rowNum)
							throws SQLException {
						Group result = new Group();
						result.setId(rs.getLong("ID"));
						result.setName(rs.getString("NAME"));
						result.setVisaLeader(rs.getString("VISA_LEADER"));
						return result;
					}
				});
	}

	@Override
	public void update(final Group transientObject) {
		getJdbcTemplate().update(SQL_UPDATE, transientObject.getName(),
				transientObject.getVisaLeader(), transientObject.getId());
	}

	@Override
	public void delete(Group persistedObject) {
		getJdbcTemplate().update(SQL_DELETE, persistedObject.getId());
	}

	@Override
	public List<Group> getAll() {
		return getJdbcTemplate().query(SQL_GET_ALL, new RowMapper<Group>() {
			@Override
			public Group mapRow(ResultSet rs, int rowNum) throws SQLException {
				Group result = new Group();
				result.setId(rs.getLong("ID"));
				result.setName(rs.getString("NAME"));
				result.setVisaLeader(rs.getString("VISA_LEADER"));
				return result;
			}
		});
	}
}
